<?php
/**
 * Page that you can export references from
 * Has these main functions
 * 1. Provide list of exports to the filter output (got from local/references)
 * The list is manually updated in this file to filter any that aren't required and to send any that require some user interaction to this page (non ajax)
 * 2. Any "exports" are attempted to be run via ajax using this page
 * For ajax requests that fail/non-ajax users or for download types exports using the filter can use this screen in browser
 *
 * @copyright &copy; 2009 The Open University
 * @author j.platts@open.ac.uk
 * @author Author_Name_2@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package filter/references
 */
require_once(dirname(__FILE__).'/../../config.php');

@require_once(dirname(__FILE__).'/../../local/references/export.php');
@require_once(dirname(__FILE__).'/../../local/references/apibib/apibib_lib.php');

class references_filter_export extends references_export {
    public static $inst;

    //NULL if not submitted to this page from itself, or name of option if did
    private $submitted;

    private static $formatlist = array();

    private $courseid = 0;

    //FILTER SPECIFIC
    //return list of export
    public static function get_formats() {
        $retarray = array();
        if (isset(self::$formatlist[0])) {
            //save doing this multiple times on a page
            return self::$formatlist;
        }
        for ($a=0, $max=count(self::$inst->formats); $a<$max; $a++) {
            $curformat = &self::$inst->formats[$a];
            if (isset($curformat['type']) && self::$inst->get_format_can_export($curformat)) {
                $retarray[] = $curformat;
            }
        }
        return $retarray;
    }

    /*
     * Creates a reference xml tag based on the query string of page
     * returns string
     */
    public static function return_xml_from_getvars() {
        $return = '<reference>';
            //custom query string handling as may have multiple occurances a param
            $qs = explode('&', $_SERVER['QUERY_STRING']);
            foreach ($qs as $posted) {
                $postval = explode('=', $posted);
                if ($postval[0] != 'button' && $postval[0] != 'info') {
                    $return .= '<'.$postval[0].'>'.str_replace('&', '&amp;', urldecode($postval[1])).'</'.$postval[0].'>';
                }
            }
        $return .= '</reference>';
        return htmlspecialchars($return, ENT_QUOTES, 'utf-8', true);
    }

    //override references_export functions with code that is different due to alternate submit
    /**
     * Works out whether returning to the form after submitting
     * @return string: format name or null if not submitted
     */
    protected function return_submitted() {
        global $_REQUEST;
        //look at the posted vars - select menu will be called select_...
        foreach ($_REQUEST as $posted => $postval) {
            if ($posted == 'menu' && $postval == 'true') {
                //submitted from the user menu generated by this page: use original function
                return parent::return_submitted();
            }
            if (strpos($posted, 'refselect_') === 0) {
                $formats = &$this->formats;
                //loop thru all the available formats and check against selected
                for($a=0, $max = count($formats); $a<$max; $a++) {
                    if ($formats[$a]['name'] == $postval) {
                        return $postval;
                    }
                    if ($formats[$a]['name'] == substr($postval, 0, strpos($postval, ':'))) {
                        return substr($postval, 0, strpos($postval, ':'));
                    }
                }
            }
            if (strpos($posted, 'button')===0) {
                if ($postval == 'null') {
                    //no option selected - show menu
                    //print_object($HTTP_GET_VARS);
                    return 'none';
                }
                $formats = &$this->formats;
                //loop thru all the available formats and check against selected
                for ($a=0, $max=count($formats); $a<$max; $a++) {
                    if ($formats[$a]['name'] == $postval) {
                        return $postval;
                    }
                    if ($formats[$a]['name'] == substr($postval, 0, strpos($postval, ':'))) {
                        return substr($postval, 0, strpos($postval, ':'));
                    }
                }
            }
        }
        return null;
    }

    public function __construct() {
        if (isset(self::$inst)) {
            return self::$inst;
        }
        GLOBAL $COURSE, $CFG, $DB;

        $this->initexport();
        //populate list of exports, manually flag if any cannot use ajax ['noajax']=true;
        for ($a=0, $max=count($this->formats); $a<$max; $a++) {
            $curformat= &$this->formats[$a];
            if ($curformat['name'] == 'MoodleFilter' || $curformat['name'] == 'BIBO_RDFa') {
                $curformat['noajax'] = true;
            }
        }

        //Always need to setup formats - only continue if display page etc
        $xml = optional_param('xml', '', PARAM_RAW);

        $button = optional_param('button', '', PARAM_RAW);

        //work out if initialsing this class (to get menu opts) or submitting to page
        if ($xml == '' && $button == '') {
            return;
        }

        //get info from the info param, this includes sesskey and course name

        $info = explode('~~', required_param('info', PARAM_RAW));

        //get our actual course id from info param sent
        if (isset($info[2])) {
            if ($course = $DB->get_record('course', array('id' => $info[2]))) {
                $COURSE = $course;
                $this->courseid = $info[2];
            }
        }

        if (!confirm_sesskey($info[0])) {
            print_error('confirmsesskeybad');
        }

        if ($xml == '') {
            //Submitted with no xml need to get from qstring + show menu
            $this->printhead();
            $menopts = new stdClass();
            $menopts->post = $CFG->wwwroot.'/filter/references/export_references.php';
            $menopts->hidden = array('xml', 'info', 'menu');
            $menopts->hiddenvals = array(self::return_xml_from_getvars(), implode('~~', $info), 'true');
            echo $this->return_export_menu($menopts);
            $this->printfoot();
            return;
        }

        $xml = stripslashes($xml);

        //add xml declaration to xml string so it is valid
        $xml = '<?xml version="1.0" encoding="utf-8"?>'.$xml;

        //check if coming to this page after submitting one of the export options
        $this->submitted = $this->return_submitted();
        if ($this->submitted == null) {
            //no submit
            return;
        } else {
            //page has been submitted to itself do something
            $submittedtype = $this->return_format_export_type($this->submitted);

            $options = new stdClass();
            $options->styles = '';
            $options->filename = 'reference';
            $options->coursename = $info[1];
            $options->ajax = optional_param('ajax', 'false', PARAM_TEXT);//in case export needs to know if this is by ajax
            $referurl = urldecode(optional_param('referer', '', PARAM_RAW));//use referer from menu if there
            if ($referurl == '') {
                $referurl = get_referer(false);
            }
            $options->redirect = $referurl;

            //print header if export type as there may be user interaction
            if ($submittedtype == self::EXPORT) {
                $this->printhead();
            }

            //call export function
            if ($this->start_export_action($this->submitted, $xml, $options) !== false) {
                //assume success unless told otherwise
                //write a hidden success message - this can be picked up by ajax calls
                echo('<div id="success" style="display:none">##success##</div>');
            }else{
                print_error('refexport_error', 'references', $options->redirect);
            }

            //print footer as an export fucntion
            if ($submittedtype == self::EXPORT) {
                $this->printfoot();
            }

        }

    }

    private function printhead() {
        global $COURSE, $OUTPUT, $PAGE;
        $actname = get_string('defaultactname','filter_references');
        $referurl = urldecode(optional_param('referer','',PARAM_RAW));//use referer from menu if there
        if ($referurl == '') {
            $referurl = get_referer(false);
        }

        //try and be clever and work out what activity we came from using the referer url
        if (strpos($referurl, 'mod/ouwiki/') !== false) {
            $params = array();
            $params = parse_url($referurl);
            parse_str($params['query'], $params);
            if (isset($params['id'])) {
                $actname = get_coursemodule_from_id('ouwiki', $params['id'], $COURSE->id)->name;
            }
        } else if (strpos($referurl, 'mod/forumng/') !== false || strpos($referurl, 'mod/forum/') !== false) {
            $actname = 'Forum';
        } else if (strpos($referurl, '/blog/') !== false || strpos($referurl, '/ou/blog/') !== false) {
            $actname = 'Blog';
        }

        if ($this->courseid != 0) {
            require_login($this->courseid, false);
        } else {
            require_login(0, false);
            $PAGE->set_context(context_system::instance());
        }
        $PAGE->set_url('/filter/references/export_references.php');
        $PAGE->navbar->add($actname, $referurl);
        $PAGE->navbar->add(get_string('exporttitle', 'filter_references'));

        $PAGE->set_title(get_string('exporttitle', 'filter_references'));
        echo $OUTPUT->header();
        //print_header_simple(get_string('exporttitle','filter_references'),'',$navigation,'',$this->return_headerlibs());
        echo $OUTPUT->box_start();
    }

    private function printfoot() {
        global $OUTPUT;
        echo $OUTPUT->box_end();
        global $COURSE;
        echo $OUTPUT->footer();
    }
}

references_filter_export::$inst=new references_filter_export();
?>